package com.gxgeek.springdata.domain.template.dao;

import com.gxgeek.springdata.common.util.JDBCUtil;
import com.gxgeek.springdata.domain.StudentDAO;
import com.gxgeek.springdata.domain.jdbc.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * Created by gx on 2017/4/21.
 */
@Repository
public class StudentDAOJdbcTemplateImpl implements StudentDAO {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Override
    public List<Student> query() {
        List<Student> studentList = new ArrayList<>();
        String sql = "select * from student";
        studentList = jdbcTemplate.query(sql, new Student());
        return studentList;

    }


    @Override
    public int save(Student ...students) {
        List<Student> studentList = Arrays.asList(students);
        String sql = "INSERT   student (name ,age)VALUES (?,?)";
        int  result = jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement preparedStatement, int i) throws SQLException {
                preparedStatement.setString(1,studentList.get(i).getName());
                preparedStatement.setInt(2,studentList.get(i).getAge());
            }
            @Override
            public int getBatchSize() {
                return studentList.size();
            }
        }).length;
        return result;
    }
}
